package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.sso.controller.OSSContorller;
import com.tanhua.sso.mapper.UserInfoMapper;
import com.tanhua.sso.enums.SexEnum;
import com.tanhua.sso.pojo.User;
import com.tanhua.sso.pojo.UserInfo;
import com.tanhua.sso.vo.FaceEngineService;
import com.tanhua.sso.vo.PicUploadResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;
@Service
public class UserinfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private PicUploadService picUploadService;
    @Autowired
    private FaceEngineService faceEngineService;

    @Autowired
    private loginService loginService;

    public boolean saveUserInfo(Map<String, String> param, String token) {
        //校验token是否存在，不存在则返回false
        User user=loginService.queryUserByToken(token);
        if (null ==user){
            return false;
        }
        //如果存在则之间创建信息
        UserInfo userInfo=new UserInfo();
        userInfo.setUserId(user.getId());
        //通过以什么什么结尾来设置男女性别，1就是男，2就是女
        userInfo.setSex(SexEnum.MAN);
        //设置昵称
        userInfo.setNickName(param.get("nickname"));
        //设置生日
        userInfo.setBirthday(param.get("birthday"));
        //设置城市
        userInfo.setCity(param.get("city"));
        return userInfoMapper.insert(userInfo)==1;
    }
        //查看图片是否为人像，如果是的话就上传
    public boolean saveUserLogo(MultipartFile file,String token){
        //校验token
        User user=loginService.queryUserByToken(token);
        if (null ==user){
            //如果等于null，返回false
            return false;
        }
        try {
            //通过人脸识别就上传，否则返回false
            boolean b = faceEngineService.checkIsPortrait(file.getBytes());
            if (!b){
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        PicUploadResult upload = picUploadService.upload(file);
        if (StringUtils.isEmpty(upload.getName())) {
                //上传失败
                return false;
            }
        //否则就是上传成功
        //将图片保存到头像
        UserInfo userInfo=new UserInfo();
        userInfo.setLogo(upload.getName());

        QueryWrapper<UserInfo>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getId());

        return userInfoMapper.update(userInfo,queryWrapper)==1;

    }

}
